from time import sleep
import datetime
from dateutil.relativedelta import relativedelta
from sys import path as path2

import requests
from bs4 import BeautifulSoup
from rich import print as rprint

# 将 Service 的路径加入 python 搜索模块的列表
path2.append('c:/users/tian/desktop')
from Service import service, ua

def req(url):
    while True:
        try:
            r = requests.get(url, headers={'user-agent': ua.ua}, timeout=3)
            code = r.status_code
            if code == 200:
                break
            elif code == 403:
                rprint('[red]IP 被禁，切换代理')
            else:
                rprint(f'[red]状态码 {code}，请求异常，重连中。。。')
        except:
            rprint('[red]连接超时，重连中。。。')
            sleep(2)
    soup = BeautifulSoup(r.text, 'lxml')
    return soup

def parse(pageIdx):
    node_h2 = req(f'https://mrcong.com/page/{pageIdx}')('h2')
    new = out = 0
    for h2 in node_h2:
        if out == 3:
            break
        title = h2.a.string
        if service.query('select * from mr where title=?', (title,)) != []:       # 已记录
            rprint(f'[green]【{title}】已记录')
            out += 1
            continue
        tag = 'A' if title.split()[0] in ["XIUREN", "YouMi", "XiaoYu", 'HuaYang', 'MFStar', 'IMISS'] else 'B'
        url = h2.a.attrs['href']
        _soup = req(url)
        _node_p = _soup('p', style='text-align: center;')
        _links = [p.a.attrs['href'] for p in _node_p]
        link1 = ' | '.join(_links[:len(_links)//2])
        link2 = ' | '.join(_links[len(_links)//2:])
        sizeList = list(_soup.find('div', class_='box-inner-block').stripped_strings)
        for c in sizeList:
            if 'GB' in c or 'MB' in c:
                size = c
        recordDate = today
        service.exec('insert into mr(tag, title, url, link1, link2, size, recordDate) values (?, ?, ?, ?, ?, ?, ?)', (tag, title, url, link1, link2, size, recordDate))
        new += 1
        rprint(f'{new}. {title}\n{link1}')

def local(date):
    results = service.query('select title, link1 from mr where recorddate=?', (date,))
    num = 0
    for result in results:
        num += 1
        title, link1 = result
        rprint(f'{num}. {title}\n{link1}')

if __name__ == '__main__':
    service.path = 'd:/data/mr.db'
    today = datetime.date.today().isoformat()

    choice = input('输入选择（回车=>网络，其他=>本地）：')
    if choice == '':
        i = 1
        conti = False
        while True:
            if conti:
                break
            parse(i)
            while True:
                c = input('是否继续？(y/n)')
                if c in 'yY':
                    i += 1
                    break
                elif c in 'nN':
                    conti = True
                    break
                else:
                    rprint('输入错误，重新输入')
    else:
        while True:
            day = input('输入日期（回车==>今天，n==>过去第n天）：\n')
            if day == '':
                date = today
                break
            elif type(eval(day)) == int:
                date = datetime.date.today() - relativedelta(days=eval(day))
                break
            else:
                print('输入有误，重新输入')
        local(date)



